//DATA INPUT PAGE================================================================================================
$(document).ready(function() {
    load_accordion();
    adjust_menu_itens();
    load_time_picker_anim();
    load_time_picker_triggers();
});
function load_accordion(){
    $( "#courses_accordion" ).accordion({
        collapsible: true,
        active: false,
        beforeActivate: function( event, ui ) {
            if(ui.newHeader.hasClass("editing")) 
                event.preventDefault();
        },
        activate: function(event, ui){
            if(ui.newHeader.length){
                $("html, body").animate({
                    scrollTop: ($(ui.newHeader).offset().top)
                 }, 1000);
            }
        }
    });
}
function adjust_menu_itens(){
    //dynamic css for menu itens
    var number_of_buttons = 0;
    $("#menu ul a").each(function(){
        number_of_buttons++;
    });
    
    if(number_of_buttons==8){ 
        $("#menu a").css("padding","0px 20px 0px 15px");
    }
}

//******************************************************************************************************
//*TIMEPICKER FUNCTIONALITIES START HERE
//******************************************************************************************************
var initial_textfield_value;
function load_time_picker_anim(){
    $(".time_picker").each(function(){
        $(this).find('div').bind({
            mouseenter: function(){
                $(this).toggleClass('entered')
            },
            mouseleave: function(){
                $(this).toggleClass('entered')
            },
            click: function(){
                if(!$(this).hasClass('selected')){
                    $(".time_picker div").each(function(){
                        $(this).removeClass('selected');
                    });
                }
                //set selected time into the input field
                $("#"+$(this).parent().find(".focused_time_field_id").html()).val($(this).find(".time_picked").html());
                $(this).toggleClass('selected');
            },
        });
    });
    $(".time_picker").mouseout(function(){
        var timefield = $("#"+$(this).find(".focused_time_field_id").html());
        if(timefield.length===0) {
            return;
        }
        else if(!timefield.is(":hover") && !timefield.is(":focus")){
//            alert("here");
            timefield.parent().find(".active_tp").each(function(){
                $(this).removeClass("active_tp");
            });
            $(this).parent().find(".time_picker").each(function(){
                $(this).remove();
            });
            }
    });
}
function load_time_picker_triggers(){
    $(".time").focusout(function(){
        //detects changes of the start time, for auto-adjusting the end time automatically
        //it also calls the PAIR validation function 
        auto_adjust_timepickers_new_time_difference($(this),initial_textfield_value);
       
        var time_picker = $(this).parent().find(".time_picker");
        var timefield = $(this);
        if(time_picker.length===0) return;
        else if(time_picker.length>1){
            for(var i=1; i<time_picker.length;i++){
                time_picker[i].remove();
            }
            time_picker = time_picker[0];
        }
        setTimeout(function(){
            if(!time_picker.is(":focus") && !time_picker.is(":hover")){
                time_picker.remove();
                timefield.parent().find(".active_tp").each(function(){
                    $(this).removeClass("active_tp");
                });
            }
        },100);
    });
    //TRIGGERS THE TIMEPICKER for THIS TEXTFIELD
    $(".time").focus(function(){
        var valid_format_textfield  = validate_textfield_hours_format($(this));
        
        //saves the current value of the start time, if valid, for auto-adjusting the end time automatically
        if($(this).hasClass("class_start") && valid_format_textfield){
            initial_textfield_value = $(this).val();
        }else{
            initial_textfield_value = "";
        }
        
        remove_all_created_timepickers();
        $(this).parent().append($(".time_picker").clone().removeClass("main_copy").css("display","block"));
        $(this).addClass("active_tp");//marks active time picker
        
        $(this).parent().find(".time_picker")
                .find(".focused_time_field_id").html($(this).attr("id")).hide();
        $(this).parent().find(".time_picker").position({
            of: $(this),
            my: "left top",
            at: "left bottom",
            collision: "none none"
        });
//        var valid_hours = validate_form_hours_format($(this).parents('form:first').attr("id"));
        if(valid_format_textfield) {
            texfield_to_timepicker($(this));
        }
        auto_adjust_end_timepicker_offsets($(this));
        adjust_scrolls_for_timepicker($(this));
        load_time_picker_anim();
    });
    $(".time").keyup(function(){
        validate_textfield_hours_format($(this));
        texfield_to_timepicker($(this));
    });
}
//applies the difference between the start time's and end time's textfields into the end_time timepicker.
//detects changes of the start time, for auto-adjusting the end time automatically
//TO BE CALLED ON FOCUSOUT OF A TEXTFIELD
function auto_adjust_timepickers_new_time_difference(time_textfield,initial_textfield_value){
        setTimeout(function(){ //gives time for the timepicker. it may make changes in the textfield and needs time to effectivate it
            var end_timefield = time_textfield.parent().find(".class_end");
            if(time_textfield.hasClass("class_start")//this function should only be triggered by the start time field
                && !time_textfield.hasClass("format_invalid")
                && time_textfield.val()!==initial_textfield_value
                && validate_time_string(initial_textfield_value)
                && validate_time_string(time_textfield.val())
                && validate_time_string(end_timefield.val())
            ){
               var initial = parseTime(initial_textfield_value);
               var initial_mins = initial.hh*60 + initial.mm;
               
                var current = parseTime(time_textfield.val());
               var current_mins = current.hh*60 + current.mm;
               
                var time_difference_mins = current_mins - initial_mins;
               
                var end_time = parseTime(end_timefield.val());
                var end_time_mins = end_time.hh*60 + end_time.mm;
               
               //validates difference in relation to the initial hour value=> because the new one should generate another end time
//            applies the time difference in the start time onto the end time
               if(end_time_mins>=initial_mins && time_difference_mins!=0){//validates format and order
                //detects and change the end time
                    var hours; 
                    var minutes;
                    
                    //atribuição de valores 
                    if(end_time_mins+time_difference_mins < 0){ //floor
                        hours = minutes = 0;
                    }else if(end_time_mins+time_difference_mins > 24*60) {//ceil
                        hours = 23;
                        minutes = 59;
                    }else{
                        hours= end_time.hh + parseInt((time_difference_mins-(time_difference_mins%60))/60);
                        minutes= end_time.mm+(time_difference_mins%60);
                    }
                    
                    if(minutes<0){
                        hours--;
                        minutes += 60;
                    }else if(minutes>=60){
                        hours++;
                        minutes -= 60;
                    }
                    //make it 2 digit
                    end_timefield.val((hours<10?"0":"")+hours+":"+(minutes<10?"0":"")+minutes);
                    
                    //adjustment calls for quick change (via TAB) between start/end time textfields
                    validate_textfield_hour_PAIR(end_timefield);
                    texfield_to_timepicker(end_timefield);
                    auto_adjust_end_timepicker_offsets(end_timefield);
                    adjust_scrolls_for_timepicker(end_timefield);
                }else 
                    initial_textfield_value="";
            }else 
                initial_textfield_value="";
        },200);
}
function auto_adjust_end_timepicker_offsets(textfield){
    if(!validate_textfield_hour_PAIR(textfield)){
        return false;
    }
    
    var end_timestamp ,start_timestamp;
    var class_time = textfield.parents(".class_time:first");
    
    //seta variaveis de tempo
    class_time.find(".class_start").each(function(){
        if(validate_textfield_hours_format($(this))){
            start_timestamp = parseTime($(this).val());
            start_timestamp = new Date(2000,0,1,start_timestamp.hh,start_timestamp.mm);
        }else return false;
    });
    //compara e calcula a diferença para o canvas
    class_time.find(".time_picker").each(function(){
        //se for um time picker de horario de fim, seta as diferenças
        if($("#"+$(this).find(".focused_time_field_id").html()).hasClass("class_end")){
            $(this).find(".time_picked").each(function(){
                end_timestamp = parseTime($(this).html());
                end_timestamp = new Date(2000,0,1,end_timestamp.hh,end_timestamp.mm);
                var  time_cell = $(this).parent();
                if(end_timestamp>start_timestamp){
                    time_cell.show();
                    var diff_time = (end_timestamp.getHours()*60+end_timestamp.getMinutes()) 
                            - (start_timestamp.getHours()*60+start_timestamp.getMinutes());
                    
                    //adjusting time format 
                    var minutes = diff_time%60;
                    var hours = parseInt((diff_time-minutes)/60);
                    var diff_display = " ("+((hours>0)?hours+"h":"");//set hours in display
                    diff_display+=((minutes>0)?minutes+"m":"") + ")";
                    
                    time_cell.find(".offset").html(diff_display);
                }else{
                    time_cell.hide();
                }
            });
        }
    });
}

//parseTime("12:00 AM"); // {hh:  0, mm: 0}
//parseTime("12:00 PM"); // {hh: 12, mm: 0}
//parseTime("01:00 PM"); // {hh: 13, mm: 0}
//parseTime("23:00");    // {hh: 23, mm: 0}
function parseTime(s) {
    var part = s.match(/(\d+):(\d+)(?: )?(am|pm)?/i);
    var hh = parseInt(part[1], 10);
    var mm = parseInt(part[2], 10);
    var ap = part[3] ? part[3].toUpperCase() : null;
    if (ap === "AM") {
        if (hh == 12) {
            hh = 0;
        }
    }
    if (ap === "PM") {
        if (hh != 12) {
            hh += 12;
        }
    }
    return { hh: hh, mm: mm };
}
function remove_all_created_timepickers(){
    $(".time_picker").each(function(){
        if(!$(this).hasClass("main_copy"))
            $(this).remove();
    });
    $(".active_tp").each(function(){
        $(this).removeClass(".active_tp");
    });
}
//if there's a value into the texfield, selects it into the time picker
function texfield_to_timepicker(textfield){
    var field_val = textfield.val();
    if(!validate_time_string(field_val)){
        return false;
    }
    field_val = field_val.split(":");

    if(field_val.length>=2){
        var aux = field_val[1].split("");
        switch(Math.round(parseInt(field_val[1])/30)){
            case 0: 
                field_val[1] = "00";
                break;
            case 1:
                field_val[1] = "30";
                break;
            case 2:
                field_val[1] = "00";
                field_val[0] = parseInt(field_val[0]);
                field_val[0] += parseInt(field_val[0])<23?1:0;//increments the hour field
                field_val[0] = ((parseInt(field_val[0]) < 10)? "0":"") + parseInt(field_val[0]);
                break;
        }
        
        field_val = field_val[0]+":"+field_val[1];
    }else return false;
    textfield.parent().find(".time_picked").each(function(){
        if(validate_time_string($(this).html())
        && field_val===$(this).html()){
            $(this).parent().parent().find(".selected").removeClass("selected");
            $(this).parent().addClass("selected");
        } 
    });
    return true;
}
function adjust_scrolls_for_timepicker(textfield){
    //scrolls accordion_element_content
    var time_picker = textfield.parent().find(".time_picker");
    if(time_picker.length!=1)
        return;
    var accordion_element_content = time_picker.parents(".accordion_element_content:first");
    var accordion_element_title_height = $(".accordion_element_title:first").height() + 2*parseInt($(".accordion_element_title:first").css('padding-top'));

    $("html, body").animate({
        scrollTop: (accordion_element_content.offset().top - accordion_element_title_height)
     }, 1000);
    
//    ajusta scroll somente se ha partes do timepicker que nao estao visiveis
    if(!isScrolledIntoView(time_picker)){
//        FORA DO CAMPO DE VISÃO ATUAL DO SCROLL. AJUSTA PARA QUE O FUNDO DO TIME PICKER SE ALINHE AO DO accordion_element_content
        //calcula offset
        var docViewTop = accordion_element_content.offset().top;// - parseInt(accordion_element_content.css("padding-top").replace("px",""));
        var docViewBottom = docViewTop + accordion_element_content.height()
                + parseInt(accordion_element_content.css("padding-bottom").replace("px",""))
                + parseInt(accordion_element_content.css("padding-top").replace("px",""));
        var elemTop = time_picker.offset().top;// + parseInt(accordion_element_content.css("padding-top").replace("px",""));;
        var elemBottom = elemTop + time_picker.height();// + parseInt(accordion_element_content.css("padding-bottom").replace("px",""));
        var offset = elemBottom - docViewBottom;
        accordion_element_content.animate({
            scrollTop: (accordion_element_content.scrollTop() + offset )
         }, 1000);
    }
    
    //correção de falhas: previne que time picker saia de baixo do timefield
    accordion_element_content.scroll(function(){
        var time_picker = accordion_element_content.find(".class_hours:first .time_picker");
        if(time_picker.length){
            time_picker.position({
                of: $("#"+time_picker.find(".focused_time_field_id").html()),
                my: "left top",
                at: "left bottom",
                collision: "none none"
            });
        }
    });
    
    //scrolls time_picker until the selected cell
    var selected = time_picker.find(".selected");
    var selected_scroll;
    
    if(selected.length===0 || selected.length>=2) return;
    else selected_scroll = parseInt(selected.position().top);
    
    if(selected_scroll>=60) selected_scroll-=60;
    else selected_scroll = 0;
    
    textfield.parent().find(".time_picker").scrollTop(selected_scroll);
}
function isScrolledIntoView(timepicker){
    var accordion_element_content = timepicker.parents(".accordion_element_content:first");
    var docViewTop = accordion_element_content.offset().top;// - parseInt(accordion_element_content.css("padding-top").replace("px",""));
    var docViewBottom = docViewTop + accordion_element_content.height()
            + parseInt(accordion_element_content.css("padding-bottom").replace("px",""))
            + parseInt(accordion_element_content.css("padding-top").replace("px",""));

    var elemTop = timepicker.offset().top;// + parseInt(accordion_element_content.css("padding-top").replace("px",""));;
    var elemBottom = elemTop + timepicker.height();// + parseInt(accordion_element_content.css("padding-bottom").replace("px",""));

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
}
//******************************************************************************************************
//*TIMEPICKER FUNCTIONALITIES END HERE
//******************************************************************************************************

function save_institution(formId){
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/save_institution",
            type: 'POST',
            data: $('#'+formId).serializeArray(),
            success: function(value){
                    session_expired_test(value);
                    $("#institution").html(value);
                    $("#new_course").show();
                    }
    });
    return false;
}
function save_new_course(formId){
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/save_course",
            type: 'POST',
            data: $('#'+formId).serializeArray(),
            success: function(value){
                    session_expired_test(value);
                    $("#courses_accordion").prepend(value);
                    $( "#courses_accordion" ).accordion("destroy");
                    load_accordion();
                }
    });
    return false;
}
function edit_course(form_id){
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_course",
            type: 'POST',
            data: $('#'+form_id).serializeArray(),
            success: function(value){
                try{
                   var json = JSON.parse(value);
                   if(json.redirect == true){
                       alert("Sessão Expirada!");
                       window.location.reload();
                   }else{
                       $("#course"+json.course_id+"_title_div").html(json.title);
                       $("#course"+json.course_id+"_content_div").html(json.content);
                       $('.course_display_element').remove();
                       $("#course"+json.course_id+"_title_div").effect("shake", { times:5 }, 1000);
                   }
                }catch(e){
                    alert("Ocorreu um erro");
                }
             }
    });
    return false;
}
function remove_course(course_id){
    if (confirm("Realmente deseja remover esta matéria e todas as suas turmas?")==true){
        $.ajax({
                url: URL_ROOT+"action/grademagica/remove_course",
                type: 'POST',
                data: "course_id="+course_id,
                success: function(value){
                    session_expired_test(value);
                    if(value=="ok"){
                       $( "#courses_accordion" ).accordion({
                            collapsible: true,
                            active:false
                        });
                       $("#course"+course_id+"_title_div").fadeOut(400, function(){
                           $("#course"+course_id+"_title_div").remove();
                           $("#course"+course_id+"_content_div").remove();
                           $( "#courses_accordion" ).accordion("destroy");
                           load_accordion();
                       });
                    }
                 }
        });
     }
}
function save_class(formId){
    if(!validate_form_hours_format(formId)) return false;
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/save_class",
            type: 'POST',
            data: $('#'+formId).serializeArray(),
            success: function(value){
                session_expired_test(value);
                $("#"+formId).parent().parent().find(".saved_classes").prepend(value);
                }
    });
    $('#'+formId)[0].reset();
    return false;
}
function cancel_class_edit(button_id){
    var form_id = $("#"+button_id).parents("form:first").attr("id");
    $.ajax({
            url: URL_ROOT+"action/grademagica/load_class",
            type: 'POST',
            data: $('#'+form_id).serializeArray(),
            success: function(value){
                session_expired_test(value);
                $("#"+form_id).fadeOut(500, function(){
                    $("#"+form_id).parent().replaceWith(value);
                });
                }
    });
}
function edit_class(form_id){
    var valid_hours = validate_form_hours_format(form_id);
    if(!valid_hours){
        alert("Horário em formato não aceito");
        return false;
    }
    $('input, option, checkbox, select, button, radio').removeClass("formError");
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_class",
            type: 'POST',
            data: $('#'+form_id).serializeArray(),
            success: function(value){
                session_expired_test(value);
                $("#"+form_id).parent().replaceWith(value);
                }
    });
    return false;
}
function remove_class(class_id, class_div_id){
    if(confirm("Deseja remover esta turma e todos os seus horários?")===true){
        $.ajax({
                url: URL_ROOT+"action/grademagica/remove_class",
                type: 'POST',
                data: "class_id="+class_id,
                success: function(message){
                    session_expired_test(message);
                    if(message=="ok"){
                        $("#"+class_div_id).fadeOut(500, function(){
                            $("#"+class_div_id).remove();
                        });
                    }
                }
        });
    }
    return false;
}
function load_edit_institution_interface(institution_id){
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_institution_interface",
            type: 'POST',
            data: 'institution_id='+institution_id,
            success: function(value){
                    $("#institution").html(value);
                    }
    });
    return false;
}
function load_edit_course_interface(course_id){
    $("#course"+course_id+"_title_div").addClass("editing");
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_course_interface",
            type: 'POST',
            data: "course_id="+course_id,
            success: function(message){
                    session_expired_test(message);
                    var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                    var inner_div = $(document.createElement('div'));
                    inner_div.addClass("course_display_inner");
                    inner_div.addClass("course_display_element");
                    inner_div.html(message);

                    var close = $(document.createElement('button'));
                    close.html("Fechar");
                    close.click(function(){
                        $('.course_display_element').remove();
                        $("#course"+course_id+"_title_div").removeClass("editing");
                    });
                    close.css({"font-weight":"bold", "width":"100%"});
                    inner_div.append(close);

                    var pop = $(document.createElement('div'));
                    pop.attr('id',rand_id);
                    pop.addClass("course_display");
                    pop.addClass("course_display_element");
                    pop.css({"zIndex":"1002" , "top": ($(document).scrollTop()+100)+"px"});
//                    pop.css({"zIndex":"1002" , "top": (parseInt((100*$(document).scrollTop())/$("body").height())).toString()+"%"});
                    pop.append(inner_div);

                    var fade = $(document.createElement('div'));
                    fade.css({"zIndex":"1001"});
                    fade.attr('class','overlay_backgroud');
                    fade.addClass("course_display_element");

                    $(document.body).append(pop);
                    $(document.body).append(fade);
                    $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
}
function load_edit_class_interface(class_id, class_div_id){
    $.ajax({
            url: URL_ROOT+"action/grademagica/edit_class_interface",
            type: 'POST',
            data: "class_id="+class_id.toString(),
            success: function(message){
                var class_div = $("#"+class_div_id);
                var accordion_content = class_div.parents(".accordion_element_content:first");
                session_expired_test(message);
                class_div.html(message);
                
                //auto scrolls to make the class_div COMPLETELY visible
                accordion_content.animate(
                    {scrollTop: (class_div.offset().top - accordion_content.offset().top +accordion_content.scrollTop())}
                ,1000);
                
                load_time_picker_anim();
                load_time_picker_triggers();
                }
    });
}

//@return true if valid; false otherwise
function validate_time_string(string){
    if(/^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(string))
        return true;
    else return false;
}
//@return true for valid; false otherwise
function validate_textfield_hours_format(textfield){
    var value = textfield.val();
    if(value==="") return false;
    else if(validate_time_string(value)){
           textfield.css("backgroundColor","#FFF");
           textfield.removeClass("format_invalid");
           return true;
        }else {
             textfield.css("backgroundColor","#F99");
             textfield.addClass("format_invalid");
             return false;
         }
}

//@return true for valid; false otherwise
function validate_textfield_hour_PAIR(textfield){
       var time_end_obj;
       var time_start_obj;
       if(textfield.hasClass("class_end")){
           time_end_obj = textfield;
           time_start_obj = textfield.parent().find(".class_start");
       }else if(textfield.hasClass("class_start")){
           time_start_obj = textfield;
           time_end_obj = textfield.parent().find(".class_end");
       }
       if(!validate_textfield_hours_format(time_end_obj) || !validate_textfield_hours_format(time_start_obj)){
           return false;
       }else
           try{
               var time_end = new Date("01/01/2001 "+time_end_obj.val());
               var time_start = new Date("01/01/2001 "+time_start_obj.val());

               if(time_start >= time_end){
                   $(this).css("backgroundColor","#F99");
                   time_start_obj.css("backgroundColor","#F99");
                   $(this).addClass("time_invalid");
                   time_start_obj.addClass("time_invalid");
                   return false;
               } else{
                   if(!time_start_obj.hasClass("format_invalid")){
                       time_start_obj.css("backgroundColor","#FFF");
                       time_start_obj.removeClass("time_invalid");
                   }
                   if(!$(this).hasClass("format_invalid")){
                       $(this).css("backgroundColor","#FFF");
                       $(this).removeClass("time_invalid");
                   }
                   return true;
               }
           }catch(e){
               $(this).css("backgroundColor","#F99");
               $(this).addClass("time_invalid");
               time_start_obj.css("backgroundColor","#F99");
               time_start_obj.addClass("time_invalid");
               return false;
           }
}
function validate_form_hours_format(form_id){
    var has_invalid = false;
    //valida formato dos horarios; par a par (class_time = classe do container do par)
    $("#"+form_id+" .class_time").each(function(){
        //valida ordem e formatos
       var textfield = $(this).find(".time:first");
       if(!validate_textfield_hour_PAIR(textfield)){
           has_invalid = true;
       }
    });
    
    if(has_invalid) return false;
    else return true;
}


//GENERATE GRID PAGE================================================================================================
function generate_grids(grid_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_grid",
            type: 'POST',
            data: "grid_id="+grid_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                inner_div.addClass("grid_display_inner");
                inner_div.addClass("grid_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.grid_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("grid_display");
                pop.addClass("grid_display_element");
                pop.css({"zIndex":"1002"});
                pop.append(inner_div);

                var fade = $(document.createElement('div'));
                fade.css({"zIndex":"1001"});
                fade.attr('class','overlay_backgroud');
                fade.addClass("grid_display_element");

                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
    return false;
}
function overlay_grid(grid_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_grid",
            type: 'POST',
            data: "grid_id="+grid_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                inner_div.addClass("grid_display_inner");
                inner_div.addClass("grid_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.grid_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("grid_display");
                pop.addClass("grid_display_element");
                pop.css({"zIndex":"1002"});
                pop.append(inner_div);

                var fade = $(document.createElement('div'));
                fade.css({"zIndex":"1001"});
                fade.attr('class','overlay_backgroud');
                fade.addClass("grid_display_element");

                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
    return false;
}

function visualize_course(course_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_course",
            type: 'POST',
            data: "course_id="+course_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                var highest_index = get_highest_zIndex();
                
                inner_div.addClass("course_display_inner");
                inner_div.addClass("course_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.course_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("course_display");
                pop.addClass("course_display_element");
                pop.append(inner_div);
                pop.css({"zIndex":(highest_index+2).toString()});
                
                var fade = $(document.createElement('div'));
                fade.attr('class','overlay_backgroud');
                fade.addClass("course_display_element");
                fade.css({"zIndex":(highest_index+1).toString()});
                
                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
}
function visualize_class(class_id){
    $.ajax({
            url: URL_ROOT+"grades/visualize_class",
            type: 'POST',
            data: "class_id="+class_id.toString(),
            success: function(message){
                session_expired_test(message);
                var rand_id = "id"+Math.floor((Math.random()*10000)+1); 
                var inner_div = $(document.createElement('div'));
                var highest_index = get_highest_zIndex();
                
                inner_div.addClass("class_display_inner");
                inner_div.addClass("class_display_element");
                inner_div.html(message);

                var close = $(document.createElement('button'));
                close.html("Fechar");
                close.attr('onClick',"$('.class_display_element').remove();");
                close.css({"font-weight":"bold", "width":"100%"});
                inner_div.append(close);
                
                var pop = $(document.createElement('div'));
                pop.attr('id',rand_id);
                pop.addClass("class_display");
                pop.addClass("class_display_element");
                pop.append(inner_div);
                pop.css({"zIndex":(highest_index+2).toString()});
                
                var fade = $(document.createElement('div'));
                fade.attr('class','overlay_backgroud');
                fade.addClass("class_display_element");
                fade.css({"zIndex":(highest_index+1).toString()});
                
                $(document.body).append(pop);
                $(document.body).append(fade);
                $(".overlay_backgroud").css({"width":$(document).width(),"height":$(document).height()});
                }
    });
}

//OTHERS

